import car from '../../../config/api/car' // 引入api接口管理文件
import userapi from '../../../config/api/userapi' // 引入api接口管理文件
const dayjs = require("./dayjs");
const app = getApp()
var WxNotificationCenter = require("../../../config/WxNotificationCenter");

import {
  baseUrl
} from '../../../config/config';
Page({

  /**
   * 页面的初始数据
   */
  data: {
    item: {},
    ferenceitem: null,
    name: null, //主题
    department: null, //部门
    phoneNumber: null, //手机号
    useCarName: null, // 人员名单
    userType: 0, //麦克类型
    userTypeArr: ["公务", "出差", "其他"],
    route: null, // 路线
    fee: null, // 费用
    schedule: null, //调度

    currdriver: null, // 当前选择司机
    driverlist: [], //司机列表

    spstate: 0,
    spTypeArr: ["审核通过", "审核拒绝"],
    auditRemark: "",
    auditStatus: 0,
    canchange: false,
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {

    let str = options['item'];
    if (str) {
      let theitem = JSON.parse(decodeURIComponent(str));
      let change = options["change"];
      if (change) {
        this.setData({
          canchange: change
        })
      }
      this.setdatefotitem(theitem);

    } else {
      let str = options['infoitem'];
      console.log(str);
      if (str) {
        let theitem = JSON.parse(decodeURIComponent(str));
        this.setData({
          item: theitem
        })
        //加载详情
        this.loadData();
      }
    }
    this.loadDriver();
    var that = this
    WxNotificationCenter.addNotification('selectcar', that.selectcar, that)
    WxNotificationCenter.addNotification('selectdrivers', that.selectdriver, that)
  },

  //加载司机列表
  loadDriver() {
    let vm = this;
    let obj = {
      "pageNo": 1,
      "pageSize": 9999,
    };
    if (this.data.startTime) {
      obj["startTime"] = this.data.startTime;
      obj["endTime"] = this.data.endTime;
    }
    userapi.getDriver(obj, function (res) {
      let list = res.data.data;
      console.log(list);
      vm.setData({
        driverlist: list
      });
    })
  },
  setdatefotitem(theitem) {
    if (theitem.carDetails) {
      let date = dayjs(theitem.carDetails.departureTime.replace(/-/g, "/")).format("YYYY-MM-DD");
      theitem["date"] = date;
      let stime = dayjs(theitem.carDetails.departureTime.replace(/-/g, "/")).format("HH:mm");
      theitem["stime"] = stime;
      let etime = dayjs(theitem.carDetails.returnTime.replace(/-/g, "/")).format("HH:mm");
      theitem["etime"] = etime;
    }


    this.setData({
      auditStatus: theitem.auditStatus,
      item: theitem,
      ferenceitem: theitem.fcar,
      name: theitem.name,
      department: theitem.department,
      phoneNumber: theitem.phoneNumber,
      useCarName: theitem.useCarName,
      userType: theitem.userType,
      route: theitem.carDetails ? theitem.carDetails.route : null,
      fee: theitem.carDetails ? theitem.carDetails.fee : null,
      schedule: theitem.carDetails ? theitem.carDetails.schedule : null,

      auditRemark: theitem.auditRemark,

    });
    if (theitem.driverName) {
      this.setData({
        currdriver: {
          name: theitem.driverName
        },
      });
    }
  },
  //选择司机回调
  selectdriver(res) {
    console.log(res, "selectdriver");
    this.setData({
      currdriver: res
    })
  },
  //选择车辆的回调
  selectcar(res) {
    //寻找司机
    let csj;
    //补充当前司机
    let list = this.data.driverlist;
    for (let index = 0; index < list.length; index++) {
      const element = list[index];
      if (element.id * 1 == res['carOwner'] * 1) {
        csj = element;
      }
    }
    if (csj && !this.data.currdriver) {
      this.setData({
        currdriver: csj
      });
    }

    this.setData({
      ferenceitem: res
    })
  },
  //加载详情
  loadData() {
    let vm = this;
    car.getAuditList({
      "id": vm.data.item.id,
    }, function (res) {
      let data = res.data.data[0];
      let item = vm.data.item;
      item["carDetails"] = data.carDetails;
      console.log(item);

      vm.setdatefotitem(data);

    })
  },
  onChange(event) {
    // event.detail 为当前输入的值
    console.log(event.detail);
  },
  clicktijiao() {
    //必填字段判空
    //车辆
    let ferenceitem = this.data.ferenceitem;
    if (!ferenceitem || !ferenceitem.id) {
      wx.showToast({
        title: "请选择车辆",
        icon: "none",
      })

      return;
    }



    wx.showLoading({
      title: '处理中...',
      mask: true,
    })
    //补充车辆与司机信息
    //carReservationupdateById
    let obj = {
      "id": this.data.item.id,
      "carId": this.data.ferenceitem.id,
    };
    if (this.data.currdriver) {
      obj['driverId'] = this.data.currdriver.id;
    }
    let vm = this;

    car.carReservationupdateById(obj, function (res) {
      if (res.data.status == 200) {
        vm.pigaichuli();
      } else {
        wx.hideLoading({
          success: (res) => {},
        })
        wx.showToast({
          title: res.data.msg,
          icon: "none"
        })
      }
    })

  },
  pigaichuli() {
    let state = this.data.spstate;
    let auditStatus = 3;
    if (state == 1) {
      auditStatus = 4;
    }

    let obj = {
      "auditRemark": this.data.auditRemark,
      "id": this.data.item.id,
      "auditStatus": auditStatus,
    };
    let vm = this;
    car.saveAudit(obj, function (res) {
      wx.hideLoading({
        success: (res) => {},
      })
      if (res.data.status == 200) {
        WxNotificationCenter.postNotificationName("reloadsplist");
        wx.navigateBack({
          delta: 1,
        })
      } else {
        wx.showToast({
          title: res.data.msg,
          icon: "none"
        })
      }
    })
  },

  //处理文本双向绑定问题
  onChange(e) {
    console.log(e.detail.value) //input 的 value
    console.log(e.currentTarget.dataset.prop) //data-prop 绑定的字符串，以此来确定改变的是哪个变量
    this.setData({
      [e.currentTarget.dataset.prop]: e.detail.value
    })
  },
  //处理是否选项
  shifouChange(e) {
    console.log(e.detail.value) //input 的 value
    console.log(e.currentTarget.dataset.prop) //data-prop 绑定的字符串，以此来确定改变的是哪个变量
    this.setData({
      [e.currentTarget.dataset.prop]: e.detail.value,
    })
  },
  // 处理开始时间
  changestime(e) {
    let stime = e.detail.value
    let item = this.data.item;
    item.stime = stime;
    this.setData({
      item: item
    })
  },
  // 处理结束时间
  changeetime(e) {
    let etime = e.detail.value
    let item = this.data.item;
    item.etime = etime;
    this.setData({
      item: item
    })
  },
  //点击司机
  clicksiji(e) {
    if (this.data.auditStatus != 1 || !this.data.canchange) {
      return;
    }


    let times = {
      "stime": this.data.item.startTime,
      "etime": this.data.item.endTime
    };
    wx.navigateTo({
      url: '/pages/driver/driver?timeobj=' + JSON.stringify(times),
    })
  },
  //选择车辆
  clickselectcl() {
    if (this.data.auditStatus != 1 || !this.data.canchange) {
      return;
    }

    wx.navigateTo({
      url: '/pages/vehicle/vehicle?selectcar=true&startTime=' + this.data.item.startTime + '&endTime=' + this.data.item.endTime
    })
  },
  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {
    var that = this
    WxNotificationCenter.removeNotification('selectcar', that);
    WxNotificationCenter.removeNotification('selectdrivers', that);
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },



  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})